package com.bank.backend.interceptor;

import com.bank.backend.enums.ErrorCode;
import com.bank.backend.config.JwtProperties;
import com.bank.backend.exception.BusinessException;
import com.bank.backend.mapper.UserMapper;
import com.bank.backend.model.entity.User;
import com.bank.backend.utils.JwtUtil;
import com.bank.backend.utils.UserHolder;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        if (claims == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "无效token");
        }
        Integer userId = (Integer) claims.get("userId");
        Boolean isAdmin = (Boolean) claims.get("isAdmin");
        log.info("Token解析结果 - userId: {}, isAdmin: {}", userId, isAdmin);
        // 解析用户信息，放到UserHolder
        UserHolder.setUserId(userId);
        UserHolder.setIsAdmin(isAdmin);
        // 同时设置完整的User对象
        User user = userMapper.selectById(userId);
        if (user != null) {
            UserHolder.saveUser(user);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束后，清除 ThreadLocal 中的用户信息
        UserHolder.removeUser();
    }
} 